#include <public/crc_16.h>


uint16_t CRCWord16Table[256];


/**
 * \initialize the CRC table
 */
void init_CRC_word16_table()
{
	uint16_t key16=0x1021;
	unsigned i=0;
	int j=0;

	for (i = 0; i < 256; ++i)
	{
		uint16_t reg = i << 8;

		// for all bits in a byte
		for (j = 0; j < 8; ++j)
		{
		reg = reg & 0x8000 ? (reg << 1) ^ key16 : reg << 1;
		}
		CRCWord16Table[i] = reg;
	}
}

/**
 * \function to generate the CRC setting the seed
 */
word16_t set_seed_and_calculate_CRC_word16(uint16_t _numBytes, const byte_t *_pData , word16_t seed){

		uint16_t index;
		register word16_t tempCRC;
		uint8_t top;

		//Init with 0xFFFF
		tempCRC=seed;

		//Calculate CRC
		for(index=0; index< _numBytes;index++)
		{
			top = tempCRC >> 8;
			top ^= *(_pData+index);
			tempCRC = (tempCRC << 8)^CRCWord16Table[top];
		}

	   return tempCRC;


}

/**
 * \function to generate the CRC
 */
word16_t calculate_CRC_word16(uint16_t _numBytes, const byte_t *_pData)
{
	return set_seed_and_calculate_CRC_word16(_numBytes, _pData , 0xFFFF);
}


/**
 * \function to check the CRC
 */
bool_t check_CRC_word16(uint16_t  _numBytes, const byte_t * _pData, word16_t crc)
{
	if(crc==calculate_CRC_word16(_numBytes,_pData))
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

